import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { z } from 'zod'

export default eventHandler(async (event) => {
  const q = getQuery(event)
  const schema = z.object({ childId: z.string() })
  const parsed = schema.safeParse(q)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const childId = Number(parsed.data.childId)
  if (!Number.isFinite(childId)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  await assertChildOwnership(event, childId)
  const { _sum: earn } = await prisma.pointsLedger.aggregate({ where: { childId, kind: 'earn' }, _sum: { amount: true } })
  const { _sum: spend } = await prisma.pointsLedger.aggregate({ where: { childId, kind: 'spend' }, _sum: { amount: true } })
  const { _sum: adjust } = await prisma.pointsLedger.aggregate({ where: { childId, kind: 'adjust' }, _sum: { amount: true } })
  const balance = (earn.amount ?? 0) - (spend.amount ?? 0) + (adjust.amount ?? 0)
  return { balance }
})


